import os

from networkx import read_graphml
from pygame import image, Rect, Surface



N_HEADERLINES = 4



def _make_imgs(graph):
    get_data = _get_data
    nodes = dict(graph.nodes(data=True))
    for node, atts in nodes.items():
        cellsize, rect, data = get_data(atts['data'])
        surf = Surface(rect.size)
        _size = (cellsize, cellsize)
        for m, line in enumerate(data):
            for n, cell in enumerate(line.split()):
                _rect = Rect((cellsize * m, cellsize * n), _size)
                _surf = Surface(_size)
                if cell == '1': _surf.fill((0, 0, 0))
                elif cell == '2': _surf.fill((255, 255, 255))
                elif cell == '3': _surf.fill((255, 0, 0))
                else: raise ValueError, 'value %s not recognized' % (str(cell))
                surf.blit(_surf, _rect)
        image.save(surf, atts['img'])


def _get_data(p_data):
    f_data = open(os.path.realpath(p_data))

    header = dict(f_data.readline().split() for n in xrange(N_HEADERLINES))
    data = f_data.readlines()

    ncols, nrows, cellsize = int(header['ncols']), int(header['nrows']), int(header['cellsize'])

    size = (ncols * cellsize, nrows * cellsize)
    rect = Rect((0, 0), size)

    return cellsize, rect, data



if __name__ == '__main__':
    graph = read_graphml('./resources/graph/example.graphml')
    _make_imgs(graph)
